<template>
    <van-icon
       :color="attitude === 1 ? '#ff0000' : '#777'"
       :name="attitude === 1 ? 'good-job' : 'good-job-o'"
       :loading="likeLoading"
      @click="onLike"
    />
</template>

<script>
import { addLikeAPI, deleteLikeAPI } from '../../../api/index.js'
export default {
  name: 'LikeArticle',
  props: {
    attitude: {
      type: Number,
      default: -1
    },
    articleId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      likeLoading: false // 收藏按钮加载状态
    }
  },
  methods: {
    // 收藏，取消收藏用户
    async onLike () {
      let message = '操作成功'
      try {
        // 调用接口前开启加载
        this.likeLoading = true
        if (this.attitude === 1) {
          // 已点赞，需要取消点赞
          await deleteLikeAPI(this.articleId)
          message = '取消收藏成功'
        } else {
          // 未点赞，需要添加点赞
          await addLikeAPI({
            target: this.articleId
          })
          message = '收藏成功'
        }
        // this.$emit('changeIsFollowed', !this.isFollowed)
        this.$emit('update:attitude', this.attitude === 1 ? -1 : 1)
        this.$toast.success(message)
      } catch (error) {
        console.log(error)
        message = '网络异常，请稍后重试'
        this.$toast.fail(message)
      }

      // 无论成功还是失败都需要关闭加载状态
      this.likeLoading = false
    }
  }
}
</script>

<style>

</style>
